package com.example.drainage.ui.surface

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.SurfaceView
import androidx.core.content.ContextCompat
import com.example.arm.base.BaseApplication
import com.example.drainage.R
import timber.log.Timber

class SurfaceViewDrawGif @JvmOverloads constructor(
    context: Context?,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : SurfaceView(context, attrs, defStyleAttr), SurfaceHolder.Callback, Runnable {

    private lateinit var mSurfaceHolder: SurfaceHolder

    //绘图的Canvas
    private var mCanvas: Canvas? = null

    //子线程标志位
    private var mIsDrawing = false

    //画笔
    private val mPaint: Paint = Paint()

    private var mTimeCounting = 0

    private var mDrawPointList = mutableListOf<Point>()

    private var mDrawPoint = Point(200, 200)

    private var mXDrawSize = 84 / 2

    private var mYDrawSize = 93 / 2

    private var dx = 0

    private var dy = 0

    companion object {
        private const val TAG = "DrawGif::"

        const val TIME_GIF = 1000 / 25

        val iconResList = listOf(
            R.mipmap.icon_emergency_dangerous_reservoir_00,
            R.mipmap.icon_emergency_dangerous_reservoir_01,
            R.mipmap.icon_emergency_dangerous_reservoir_02,
            R.mipmap.icon_emergency_dangerous_reservoir_03,
            R.mipmap.icon_emergency_dangerous_reservoir_04,
            R.mipmap.icon_emergency_dangerous_reservoir_05,
            R.mipmap.icon_emergency_dangerous_reservoir_06,
            R.mipmap.icon_emergency_dangerous_reservoir_07,
            R.mipmap.icon_emergency_dangerous_reservoir_08,
            R.mipmap.icon_emergency_dangerous_reservoir_09,
            R.mipmap.icon_emergency_dangerous_reservoir_10,
            R.mipmap.icon_emergency_dangerous_reservoir_11,
            R.mipmap.icon_emergency_dangerous_reservoir_12,
            R.mipmap.icon_emergency_dangerous_reservoir_13,
            R.mipmap.icon_emergency_dangerous_reservoir_14,
            R.mipmap.icon_emergency_dangerous_reservoir_15,
            R.mipmap.icon_emergency_dangerous_reservoir_16,
            R.mipmap.icon_emergency_dangerous_reservoir_17,
            R.mipmap.icon_emergency_dangerous_reservoir_18,
            R.mipmap.icon_emergency_dangerous_reservoir_19,
            R.mipmap.icon_emergency_dangerous_reservoir_20,
            R.mipmap.icon_emergency_dangerous_reservoir_21,
            R.mipmap.icon_emergency_dangerous_reservoir_22,
            R.mipmap.icon_emergency_dangerous_reservoir_23,
            R.mipmap.icon_emergency_dangerous_reservoir_24,
        )
        val drawableList = iconResList.map {
            ContextCompat.getDrawable(BaseApplication.INSTANCE, it)!!
        }
    }

    init {
        mPaint.color = Color.BLACK
        mPaint.style = Paint.Style.STROKE
        mPaint.strokeWidth = 5f
        mPaint.isAntiAlias = true
        initView()

        mDrawPointList.add(Point(100, 100))
        mDrawPointList.add(Point(200, 100))
        mDrawPointList.add(Point(200, 200))
        mDrawPointList.add(Point(200, 400))
        mDrawPointList.add(Point(200, 500))
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        mIsDrawing = true
        Thread(this).start()
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
        Timber.d(
            "surfaceChanged() called with: holder = $holder, format = $format, width = $width, height = $height"
        )
    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {
        mIsDrawing = false
    }

    override fun run() {
        while (mIsDrawing) {
            val start = System.currentTimeMillis()
            drawSomething()
            mTimeCounting = (mTimeCounting + 1) % iconResList.size
            val end = System.currentTimeMillis()
            if (end - start < TIME_GIF) {
                try {
                    Thread.sleep(TIME_GIF - (end - start))
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
            }
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        // 点击添加,新增点随移动而移动
        /*when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                mDrawPoint = Point(event.x.toInt(), event.y.toInt())
                mDrawPointList.add(mDrawPoint)
            }
            MotionEvent.ACTION_MOVE -> {
                mDrawPoint.x = event.x.toInt()
                mDrawPoint.y = event.y.toInt()
            }
            MotionEvent.ACTION_UP -> {

            }
        }*/
        // 所有点随移动而移动
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                mDrawPoint.x = event.x.toInt()
                mDrawPoint.y = event.y.toInt()
            }
            MotionEvent.ACTION_MOVE -> {
                val x = event.x.toInt() - mDrawPoint.x
                val y = event.y.toInt() - mDrawPoint.y
                mDrawPoint.x = event.x.toInt()
                mDrawPoint.y = event.y.toInt()
                dx += x
                dy += y
            }
            MotionEvent.ACTION_UP -> {

            }
        }
        return true
    }

    /**
     * 初始化View
     */
    private fun initView() {
        mSurfaceHolder = holder
        mSurfaceHolder.addCallback(this)
        isFocusable = true
        keepScreenOn = true
        isFocusableInTouchMode = true
        setZOrderOnTop(true);
        holder.setFormat(PixelFormat.TRANSPARENT);
    }

    private fun drawSomething() {
        if (mDrawPointList.isEmpty()) {
            return
        }
        try {
            //获得canvas对象
            mCanvas = mSurfaceHolder.lockCanvas()
            mCanvas?.apply {
                //绘制背景
//                drawColor(Color.TRANSPARENT)
                drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
                val drawable = drawableList[mTimeCounting]
                mDrawPointList.forEach { point ->
                    drawable.setBounds(
                        point.x - mXDrawSize + dx,
                        point.y - mYDrawSize + dy,
                        point.x + mXDrawSize + dx,
                        point.y + mYDrawSize + dy
                    )
                    drawable.draw(this)
                }
            }
        } catch (e: Exception) {
        } finally {
            if (mCanvas != null) {
                //释放canvas对象并提交画布
                mSurfaceHolder.unlockCanvasAndPost(mCanvas)
                mCanvas = null
            }
        }
    }

    fun updatePointList(list: List<Point>) {
        Log.d(TAG, "updatePointList() called with: list = $list")
        mDrawPointList.clear()
        mDrawPointList.addAll(list)
        dx = 0
        dy = 0
    }

    fun reset() {
        mDrawPointList.clear()
        dx = 0
        dy = 0
    }
}